import 'dart:convert';
import 'dart:io';
import 'dart:ui';

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/login_init_dao.dart';
import 'package:changxindianzishangwu/db/ec_cache.dart';
import 'package:changxindianzishangwu/http/base/http_urls.dart';
import 'package:changxindianzishangwu/model/base_model.dart';

//import 'package:changxindianzishangwu/im_test_login/login.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/model/we_chat_user_info_model.dart';
import 'package:changxindianzishangwu/pages/login/country_phone_page.dart';
import 'package:changxindianzishangwu/pages/login/login_account_page.dart';

//import 'package:changxindianzishangwu/pages/login/login_auth_page.dart';
import 'package:changxindianzishangwu/pages/login/login_update_info_page.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:changxindianzishangwu/widget/web_view.dart';
import 'package:dio/dio.dart' as dio;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:fluwx/fluwx.dart' as Fluwx;
import 'package:fluwx/fluwx.dart';

//import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:jverify/jverify.dart';
import 'package:provider/provider.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_callback.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';
import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart';

import 'login_binding_phone_page.dart';

class LoginInitPage extends StatefulWidget {
  LoginInitPage({Key key}) : super(key: key);

  @override
  _LoginInitPageState createState() => _LoginInitPageState();
}

class _LoginInitPageState extends State<LoginInitPage> {
  String inputText;
  String phoneCountry = "+86";
  var data;
  bool isLine = false;

  FocusNode focusNode = FocusNode(); //密码框焦点

  @override
  void initState() {
    super.initState();
    initPlatformState();
    isLine = true;
    _initWx();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    EasyLoading.dismiss();
    isLine = false;

    super.dispose();
  }

  var token;

  //
  _getVerify(inputText, phoneCountry) async {
    var areaCode = phoneCountry.substring(1, phoneCountry.length);
    print(areaCode);
    var routerWhere = await LoginInitDao.loginVerify(inputText, areaCode);
    return routerWhere;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        //收起键盘
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        appBar: TopAppBar(context, "登录/注册", automaticallyImplyLeading: false),
        backgroundColor: Colors.white,
        body: Container(
          padding: EdgeInsets.all(width(15)),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(
                height: height(45),
              ),
              Text(
                "手机号登录",
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(18),
                  fontFamily: "PingFang SC",
                  color: Color.fromRGBO(51, 51, 51, 1),
                ),
              ),
              SizedBox(
                height: height(10),
              ),
              Text(
                "未注册手机号一键登陆后将自动创建账号",
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(12),
                  fontFamily: "PingFang SC",
                  color: Color.fromRGBO(153, 153, 153, 1),
                ),
              ),
              SizedBox(
                height: height(30),
              ),
              Text(
                "手机号码",
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(13),
                  fontFamily: "PingFang SC",
                  color: Color.fromRGBO(85, 85, 85, 1),
                ),
              ),
              Row(
                children: <Widget>[
                  InkWell(
                    onTap: () {
                      Get.to(() => CountryPhonePage()).then((value) {
                        if (value == null) {
                          phoneCountry = "+86";
                        } else {
                          try {
                            phoneCountry = value;
                          } catch (e) {
                            print(e);
                          }
                        }
                      });
                    },
                    child: Row(
                      children: [
                        Text(phoneCountry),
                        SizedBox(
                          width: ScreenUtil().setWidth(16),
                        ),
                        Image.asset("images/下拉.png")
                      ],
                    ),
                  ),
                  SizedBox(
                    width: ScreenUtil().setWidth(7),
                  ),
                  Expanded(
                    child: TextField(
                      maxLines: 1,
                      onChanged: (text) {
                        inputText = text;
                      },
                      keyboardType: TextInputType.number,
                      cursorColor: Colors.greenAccent,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: "请输入新手机号码",
                        hintStyle: TextStyle(
                          fontSize: ScreenUtil().setSp(13),
                          color: Color.fromRGBO(153, 153, 153, 1),
                        ),
                      ),
                      inputFormatters: [
                        LengthLimitingTextInputFormatter(13), //最大长度
                      ],
                      onTap: () {
                        FocusScope.of(context).requestFocus(focusNode);
                      },
                      focusNode: focusNode,
                    ),
                  ),
                ],
              ),

              UniversalView().line(),
              SizedBox(
                height: height(60),
              ),
              UniversalView().longBtn("下一步", () {
                print("发送验证码");
                if (inputText == null) {
                  showToast("手机号码不能为空");
                  return;
                }
                if (inputText.length < 7) {
                  showToast("请输入正确的手机号");
                  return;
                }
                if (inputText.length > 11) {
                  showToast("请输入正确的手机号");
                  return;
                }
                _getVerify(inputText, phoneCountry);
              }),
              SizedBox(
                height: height(10),
              ),
              UniversalView().longBtnLine("一键登录", () {
                isD = true;
                isInitSuccess();
              }),

              ///账号密码登录
              _accountLogin(),
              // _yjDl(),
              Expanded(flex: 1, child: SizedBox()),

              ///微信登录
              !GetPlatform.isIOS && !wxResult ? SizedBox() : _thirdHint(),
              _wxAppleLoginView(),

              Container(
                margin: EdgeInsets.only(
                    bottom: 20, top: ScreenUtil().setHeight(20)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      "登录即表示同意",
                      style: TextStyle(
                          fontSize: ScreenUtil().setSp(13),
                          color: Color.fromRGBO(153, 153, 153, 1),
                          fontFamily: "PingFang SC"),
                    ),
                    InkWell(
                      onTap: () {
                        Get.to(WebViewExample(
                          url: HttpUrls.YH_XY,
                        ));
                      },
                      child: Text(
                        "《用户协议》",
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(13),
                            color: Color.fromRGBO(0, 220, 169, 1),
                            fontFamily: "PingFang SC"),
                      ),
                    ),
                    Text(
                      "和",
                      style: TextStyle(
                          fontSize: ScreenUtil().setSp(13),
                          color: Color.fromRGBO(153, 153, 153, 1),
                          fontFamily: "PingFang SC"),
                    ),
                    InkWell(
                      onTap: () {
                        Get.to(WebViewExample(
                          url: HttpUrls.YS_XY,
                        ));
                      },
                      child: Text(
                        "《隐私政策》",
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(13),
                            color: Color.fromRGBO(0, 220, 169, 1),
                            fontFamily: "PingFang SC"),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        resizeToAvoidBottomInset: false,
      ),
    );
  }

  Row _wxAppleLoginView() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        wxResult
            ? InkWell(
                onTap: () {
                  print("微信登录");
                  _loginWx();
                },
                child: Container(
                  margin: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
                  height: ScreenUtil().setWidth(40),
                  width: ScreenUtil().setWidth(40),
                  child: Image.asset("images/微信.png"),
                ),
              )
            : SizedBox(),
        SizedBox(
          width: width(10),
        ),
        Offstage(
          offstage: !GetPlatform.isIOS,
          child: InkWell(
            onTap: () {
              _loginApple();
            },
            child: Container(
              padding: EdgeInsets.all(2),
              decoration: BoxDecoration(
                  color: Colors.black,
                  borderRadius: BorderRadius.circular(ScreenUtil().radius(90))),
              margin: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
              height: ScreenUtil().setWidth(40),
              width: ScreenUtil().setWidth(40),
              child: Image.asset("images/ic_apple.png"),
            ),
          ),
        )
      ],
    );
  }

  Row _thirdHint() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          width: ScreenUtil().setWidth(100),
          child: Divider(
            color: Color.fromRGBO(232, 232, 232, 1),
            height: ScreenUtil().setHeight(1),
            thickness: ScreenUtil().setHeight(1),
          ),
        ),
        SizedBox(
          width: ScreenUtil().setWidth(11),
        ),
        Container(
          child: Text(
            "其他登录方式",
            style: TextStyle(
                fontSize: ScreenUtil().setSp(12),
                color: Color.fromRGBO(153, 153, 153, 1),
                fontFamily: "PingFang SC"),
          ),
        ),
        SizedBox(
          width: ScreenUtil().setWidth(11),
        ),
        Container(
          width: ScreenUtil().setWidth(100),
          child: Divider(
            color: Color.fromRGBO(232, 232, 232, 1),
            height: ScreenUtil().setHeight(1),
            thickness: ScreenUtil().setHeight(1),
          ),
        ),
      ],
    );
  }

  _accountLogin() {
    Text text = Text(
      "使用自语号登录",
      style: TextStyle(color: AppColor.colorDefaultText, fontSize: sp(15)),
    );

    return Center(
      child: Padding(
        padding: const EdgeInsets.only(top: 20),
        child: TextButton(
          onPressed: () {
            Get.to(LoginAccountPage());
          },
          child: text,
        ),
      ),
    );
  }

  ///------------------一键登录 start-----------------------------------------------
  ///
  bool isD = false;

  /// 统一 key
  final String f_result_key = "result";

  /// 错误码
  final String f_code_key = "code";

  /// 回调的提示信息，统一返回 flutter 为 message
  final String f_msg_key = "message";

  /// 运营商信息
  final String f_opr_key = "operator";

  String _result = "";
  final Jverify jverify = new Jverify();

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    // 初始化 SDK 之前添加监听
    jverify.addSDKSetupCallBackListener((JVSDKSetupEvent event) {
      print("loginAuth receive sdk setup call back event :${event.toMap()}");
    });

    jverify.setDebugMode(true); // 打开调试模式
    jverify.setup(
        appKey: AppString.JG_APP_KEY, //"你自己应用的 AppKey",
        channel: "devloper-default"); // 初始化sdk,  appKey 和 channel 只对ios设置有效
    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.

    if (!mounted) return;

    /// 授权页面点击时间监听
    jverify.addAuthPageEventListener((JVAuthPageEvent event) {
      print("loginAuth receive auth page event :${event.toMap()}");
    });
  }

  /// sdk 初始化是否完成
  void isInitSuccess() async {
    _showLoading();
    var map = await jverify.isInitSuccess();
    bool result = map[f_result_key];
    if (result) {
      print('loginAuth----初始化成功---');
      loginAuth();
    } else {
      _hideLoading();
      print('loginAuth----初始化失败---');
      if (isD) {
        showCupertinoDialog(
            context: context, builder: (context) => getDialog(context));
      }
      // _result = "sdk 初始换失败";
    }
  }

  /// SDK 请求授权一键登录
  loginAuth() async {
    var map = await jverify.checkVerifyEnable();
    bool result = map[f_result_key];
    print('loginAuth----checkVerifyEnable ${json.encode(map)}---');

    if (result) {
      bool isiOS = Platform.isIOS;

      /// 自定义授权的 UI 界面，以下设置的图片必须添加到资源文件里，
      /// android项目将图片存放至drawable文件夹下，可使用图片选择器的文件名,例如：btn_login.xml,入参为"btn_login"。
      /// ios项目存放在 Assets.xcassets。
      ///
      JVUIConfig uiConfig = JVUIConfig();
      uiConfig.navColor = Colors.white.value;
      uiConfig.navText = "登录";
      uiConfig.navTextColor = AppColor.colorDefaultText.value;
      uiConfig.navReturnImgPath = "ic_back_auth"; //图片必须存在

      uiConfig.logoWidth = 100;
      uiConfig.logoHeight = 100;
      uiConfig.logoOffsetY = 10;
      uiConfig.logoVerticalLayoutItem = JVIOSLayoutItem.ItemSuper;
      uiConfig.logoImgPath = "logo";
      // uiConfig.logoHidden = true;

      uiConfig.numberFieldWidth = 200;
      uiConfig.numberFieldHeight = 40;
      uiConfig.numFieldOffsetY = isiOS ? 20 : 120;
      // uiConfig.numFieldOffsetY = 120;
      uiConfig.numberVerticalLayoutItem = JVIOSLayoutItem.ItemLogo;
      uiConfig.numberColor = AppColor.colorDefaultText.value;
      uiConfig.numberSize = 20;

      uiConfig.sloganOffsetY = isiOS ? 20 : 160;
      // uiConfig.sloganOffsetY = 160;
      uiConfig.sloganVerticalLayoutItem = JVIOSLayoutItem.ItemNumber;
      uiConfig.sloganTextColor = AppColor.colorGrey153.value;
      uiConfig.sloganTextSize = 12;
//        uiConfig.slogan
      //uiConfig.sloganHidden = 0;

      uiConfig.logBtnWidth = 300;
      uiConfig.logBtnHeight = 44;
      uiConfig.logBtnOffsetY = isiOS ? 20 : 230;
      uiConfig.logBtnVerticalLayoutItem = JVIOSLayoutItem.ItemSlogan;
      uiConfig.logBtnText = "本机号码一键登录";
      uiConfig.logBtnTextColor = Colors.white.value;
      uiConfig.logBtnTextSize = 15;
      uiConfig.logBtnBackgroundPath = "login_btn_normal";
      uiConfig.loginBtnNormalImage = "login_btn_normal"; //图片必须存在
      uiConfig.loginBtnPressedImage = "login_btn_press"; //图片必须存在
      uiConfig.loginBtnUnableImage = "login_btn_unable"; //图片必须存在
      uiConfig.privacyHintToast =
          true; //only android 设置隐私条款不选中时点击登录按钮默认显示toast。

      uiConfig.privacyState = true; //设置默认勾选
      uiConfig.privacyCheckboxInCenter = true;
      uiConfig.privacyCheckboxHidden = true;

      uiConfig.privacyOffsetY = 30; // 距离底部距离
      uiConfig.privacyVerticalLayoutItem = JVIOSLayoutItem.ItemSuper;
      uiConfig.clauseName = "《用户协议》";
      uiConfig.clauseUrl = HttpUrls.YH_XY;
      uiConfig.clauseBaseColor = Colors.black.value;
      uiConfig.clauseNameTwo = "《隐私协议》";
      uiConfig.clauseUrlTwo = HttpUrls.YS_XY;
      uiConfig.clauseColor = AppColor.colorTheme.value;
      uiConfig.privacyText = ["登录即表示同意"];
      uiConfig.privacyTextSize = 13;
      List<JVPrivacy> privacyItemIOS = [
        JVPrivacy("用户协议", HttpUrls.YH_XY, separator: "和"),
        JVPrivacy("隐私协议", HttpUrls.YS_XY, separator: "、")
      ];
      List<JVPrivacy> privacyItemAndroid = [
        JVPrivacy("《用户协议》", HttpUrls.YH_XY, beforeName: "、\n", separator: "、"),
        JVPrivacy("《隐私协议》", HttpUrls.YS_XY, beforeName: "和", separator: "、")
      ];
      uiConfig.privacyItem = isiOS ? privacyItemIOS : privacyItemAndroid;
      // uiConfig.privacyWithBookTitleMark = true;
      uiConfig.privacyTextCenterGravity = true;
      uiConfig.authStatusBarStyle = JVIOSBarStyle.StatusBarStyleDarkContent;
      uiConfig.privacyStatusBarStyle = JVIOSBarStyle.StatusBarStyleDefault;
      uiConfig.modelTransitionStyle = JVIOSUIModalTransitionStyle.CrossDissolve;

      uiConfig.statusBarColorWithNav = true;
      uiConfig.virtualButtonTransparent = true;

      uiConfig.privacyStatusBarColorWithNav = true;
      uiConfig.privacyVirtualButtonTransparent = true;

      uiConfig.needStartAnim = true;
      uiConfig.needCloseAnim = true;
      uiConfig.enterAnim = "activity_slide_enter_bottom";
      uiConfig.exitAnim = "activity_slide_exit_bottom";

      uiConfig.privacyNavColor = Colors.white.value;
      uiConfig.privacyNavTitleTextColor = AppColor.colorDefaultText.value;
      uiConfig.privacyNavTitleTextSize = 16;
      uiConfig.privacyNavReturnBtnImage = "ic_back_auth"; //图片必须存在;

      /// 添加自定义的 控件 到授权界面
      List<JVCustomWidget> widgetList = [];

      /// 步骤 1：调用接口设置 UI
      jverify.setCustomAuthorizationView(true, uiConfig,
          landscapeConfig: uiConfig, widgets: widgetList);
      jverify.loginAuth(true).then((map) {
        print('----------${json.encode(map)}');

        /// 再，在回调里获取 loginAuth 接口异步返回数据（如果是通过添加 JVLoginAuthCallBackListener 监听来获取返回数据，则忽略此步骤）
        int code = map[f_code_key];
        String content = map[f_msg_key];
        String operator = map[f_opr_key];
        _hideLoading();
        if (code == 6000) {
          _authLoginData(content);
          return;
        }
        toast("一键登录异常：$content");

        // if (code == 2005) {
        //   toast("网络异常，请稍后尝试");
        // }
        // _result = "接口异步返回数据：[$code] message = $content";

        print(
            "通过接口异步返回，获取到 loginAuth 接口返回数据，code=$code,message = $content,operator = $operator");
      });
    } else {
      _hideLoading();
      if (isD) {
        setState(() {
          _result = "[2016],msg = 当前网络环境不支持认证";
          showCupertinoDialog(
              context: context, builder: (context) => getDialog(context));
        });
      }
    }
  }

  void _showLoading() {
    EasyLoading.show();
  }

  void _hideLoading() {
    EasyLoading.dismiss();
  }

  ///一键登录 调用接口
  void _authLoginData(String content) async {
    _showLoading();

    UserInfoModel _userinfoModel = await LoginInitDao.loginAuth(content);
    if (_userinfoModel.resultCode != 1) {
      showToast("登录失败");
      _hideLoading();
      toast(_userinfoModel.resultMsg);
      return;
    }
    _loginIm(_userinfoModel);

    // V2TimCallback value=await TencentImSDKPlugin.v2TIMManager
    //     .login(
    //   userID: _userinfoModel.data.userId,
    //   userSig: _userinfoModel.data.userSig,
    // );
    // _hideLoading();
    // if (value.code == 0) {
    //   getData();
    //   final XgFlutterPlugin tpush = new XgFlutterPlugin();
    //   tpush.setAccount(getUserId(), AccountType.UNKNOWN);
    //
    //   showToast("登录成功");
    //   return _userinfoModel.data.isFirstIn == 1
    //       ? Get.offAllNamed(
    //     "/homePage",
    //     arguments: getAppLoginToken(),
    //   )
    //       : Get.offAll(LoginUpdateInfoPage());
    // } else {
    //   showToast("登录失败");
    // }
  }

  getData() async {
    V2TimValueCallback<List<V2TimUserFullInfo>> infos = await TencentImSDKPlugin
        .v2TIMManager
        .getUsersInfo(userIDList: [EcCache.getInstance().get('userId')]);
    if (infos.code == 0) {
      Provider.of<UserModel>(context, listen: false).setInfo(infos.data[0]);
    }
  }

  CupertinoAlertDialog getDialog(context) {
    return CupertinoAlertDialog(
        content: new SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text(
                "提示",
                style:
                    TextStyle(fontSize: 16, color: AppColor.colorDefaultText),
              ),
              Text(
                AppString.authLogin,
                style:
                    TextStyle(fontSize: 13, color: AppColor.colorDefaultText),
              ),
            ],
          ),
        ),
        actions: <Widget>[
          CupertinoDialogAction(
            child: Text(
              "好的",
              style: TextStyle(fontSize: 17, color: AppColor.colorTheme),
            ),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          CupertinoDialogAction(
            child: Text(
              "取消",
              style: TextStyle(fontSize: 17, color: AppColor.colorDefaultText),
            ),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ]);
  }

  ///------------------一键登录 end-----------------------------------------------
  ///------------------微信登录 start-----------------------------------------------

  var wxResult = false;

  _initWx() async {
    Fluwx.weChatResponseEventHandler.listen((data) {
      print('WX login _result errCode:${data.errCode}');
      print('WX login _result errStr:${data.errStr}');
      if (data.errCode == 0 && isLine) {
        EasyLoading.show();

        Fluwx.WeChatAuthResponse wa = data;
        _result += '  Code:' + wa.code;
        _result += '  country:' + wa.country;
        var code;
        print('WX login _result :$_result');

        setState(() {
          code = wa.code;
          print('WX login code :$code');
          getWeChatAccessToken(code); //通过 code 获取 access_token
        });
      }
    });
    wxResult = await isWeChatInstalled;
    setState(() {
      print("WX is installed $wxResult");
    });
  }

  _loginWx() async {
    var exist = await Fluwx.isWeChatInstalled;

    if (!exist) {
      Fluttertoast.showToast(
          msg: "请先安装微信",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);
    }
    if (exist) {
      Fluwx.sendWeChatAuth(
              scope: "snsapi_userinfo", state: "wechat_sdk_demo_test")
          .then((value) {
        print('WX login _result :$value');
      });
    }
  }

  void getWeChatAccessToken(code) async {
    var url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=";
    url += "${AppString.WX_APP_ID}&secret=${AppString.APP_SECRET}&code=" + code;
    url += "&grant_type=authorization_code";
    print('WX login getWeChatAccessToken url：$url');

    //当第一次登录成功后点击退出再登录时，会报40163的错误
    // 40163 指的是使用同一个code 多次请求获取token
    //解决方法：每次请求的code都不一样，所以我们只需在传code的地方让它刷新即可

    try {
      dio.Response response = await dio.Dio().get(url);
      _result = response.data.toString();
      var data = jsonDecode(_result);
      assert(data is Map);
      var access_token = data['access_token'];
      var openid = data['openid'];
      getWeChatUserInfo(access_token, openid); //获取微信用户信息
    } catch (e) {
      EasyLoading.dismiss();
      toast("微信登录失败：$e");
      print('WX login getWeChatAccessToken error：$e');
    }
  }

  void getWeChatUserInfo(accessToken, openId) async {
    if (accessToken == null) return;

    var url = "https://api.weixin.qq.com/sns/userinfo?access_token=";
    url += accessToken + "&openid=" + openId.toString();

    try {
      dio.Response response = await dio.Dio().get(url);
      String dataStr = response.data.toString();
      print('WX login _userinfo：$dataStr');
      Map<String, dynamic> responseData = jsonDecode(dataStr);
      WeChatUserInfoModel _weChatUserinfo =
          WeChatUserInfoModel.fromJson(responseData);
      checkUserInfo(_weChatUserinfo);
    } catch (e) {
      EasyLoading.dismiss();
      toast("微信登录失败：$e");
      print('WX login _userinfo error：$e');
    }
  }

  void _loginApple() async {
    AuthorizationCredentialAppleID credential =
        await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    );

    if (credential != null) {
      // print('苹果登录 userIdentifier：${credential.userIdentifier}');
      // print('苹果登录 givenName：${credential.givenName}');
      // print('苹果登录 familyName：${credential.familyName}');
      // print('苹果登录 email：${credential.email}');
      // print('苹果登录 authorizationCode：${credential.authorizationCode}');
      // print('苹果登录 identityToken：${credential.identityToken}');
      // print('苹果登录 state：${credential.state}');
      _showLoading();

      ///强制绑定逻辑
      var _userinfoModel = await LoginInitDao.checkQrUser(LoginType.LOGIN_APPLE,
          mobileToken: credential.identityToken);

      if (_userinfoModel is BaseModel) {
        EasyLoading.dismiss();
        toast("苹果登录失败：${_userinfoModel.resultMsg}");
        // if (_userinfoModel.resultCode == 0) {
        //   WeChatUserInfoModel weChatUserInfoModel = WeChatUserInfoModel(
        //       openid: _userinfoModel.resultMsg,
        //       loginType: LoginType.LOGIN_APPLE);
        //   Get.to(LoginBindingPhonePage(
        //     weChatUserInfoModel: weChatUserInfoModel,
        //   ));
        // } else {
        //   toast("苹果登录失败：${_userinfoModel.resultMsg}");
        // }
      } else {
        print('_userinfoModel isFirstIn:${_userinfoModel.data.isFirstIn}');
        _loginIm(_userinfoModel);
      }
    }
  }

  ///微信性别返回 测试下sex
  checkUserInfo(WeChatUserInfoModel weChatUserinfo) async {
    var _userinfoModel = await LoginInitDao.checkQrUser(LoginType.LOGIN_WX,
        loginInfo: weChatUserinfo.openid);
    weChatUserinfo.loginType = LoginType.LOGIN_WX;

    if (_userinfoModel is BaseModel) {
      EasyLoading.dismiss();
      toast("微信登录失败：${_userinfoModel.resultMsg}");
      // Get.to(LoginBindingPhonePage(
      //   weChatUserInfoModel: weChatUserinfo,
      // ));
    } else {
      print('_userinfoModel isFirstIn:${_userinfoModel.data.isFirstIn}');
      _loginIm(_userinfoModel);
    }
  }

  _loginIm(_userinfoModel) async {
    var res = await TencentImSDKPlugin.v2TIMManager.login(
      userID: _userinfoModel.data.userId,
      userSig: _userinfoModel.data.userSig,
    );
    EasyLoading.dismiss();
    if (res.code == 0) {
      getData();
      final XgFlutterPlugin tpush = new XgFlutterPlugin();
      tpush.setAccount(getUserId(), AccountType.UNKNOWN);
      // showToast("登录成功");
      _userinfoModel.data.isFirstIn == 1
          ? Get.offAllNamed("/homePage", arguments: getAppLoginToken())
          : Get.offAll(LoginUpdateInfoPage());
    } else {
      showToast("IM 登录失败");
    }
  }

  ///------------------微信登录 end-----------------------------------------------

}
